package cn.kxm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.kxm.pojo.InstroageBill;
import cn.kxm.pojo.InstroageBillDetail;
import cn.kxm.pojo.PartType;
import cn.kxm.pojo.PayBill;
import cn.kxm.pojo.PayBillDetail;
import cn.kxm.service.CompanyService;
import cn.kxm.service.DictService;
import cn.kxm.service.InstroageBillDetailService;
import cn.kxm.service.InstroageBillService;
import cn.kxm.service.PartService;
import cn.kxm.service.PartTypeService;
import cn.kxm.service.PurchaseOrderBillDetailService;
import cn.kxm.service.PurchaseOrderBillService;
import cn.kxm.util.ExcelUtil;
import cn.kxm.util.MakeNewCode;
import cn.kxm.util.WorderToNewWordUtils;

@Controller
@RequestMapping("/instroageBill")
public class InstroageBillController extends BaseController {
	
	@Autowired
    private InstroageBillService instroageBillService;
	@Autowired
	private InstroageBillDetailService detailService;
	@Autowired
	private MakeNewCode makeNewCode;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private DictService dictService;
	@Autowired
	private PurchaseOrderBillService pOrderBillService;
	@Autowired
	private PurchaseOrderBillDetailService pDetailService;
	@Autowired
	private PartService partService;
	@Autowired
	private PartTypeService partTypeService;
	
	@RequestMapping("getInstroageBillList.json")
	@ResponseBody
	public Object getInstroageBills(@RequestParam(value="page",required=false)Integer page,
			                        @RequestParam(value="rows",required=false)Integer size,
			                        @RequestParam(value="findcode",required=false)String findcode,
			                        @RequestParam(value="findstartDate",required=false)Date findstartDate,
			                        @RequestParam(value="findendDate",required=false)Date findendDate,
			                        @RequestParam(value="findsupplierName",required=false)String findsupplierName
			                        ){
		System.out.println(page+">>>>>>>>>>>>>>>>>>>>>"+size);
		List<InstroageBill> bills=instroageBillService.getInstroageBillList(page, size, findcode, findstartDate, findendDate, findsupplierName);
		Map<String, Object> jsonMaps=new HashMap<String, Object>();
		Integer total=instroageBillService.findInstroageBillCount();
		int amounts=0;//数量总和
		double moneys=0;//总价总和
		for (InstroageBill instroageBill : bills) {
			amounts+=instroageBill.getBamount();
		}
		for (InstroageBill instroageBill : bills) {
			moneys+=instroageBill.getMoney();
		}
		jsonMaps.put("isFooter", true);
		jsonMaps.put("customName", "合计");
		jsonMaps.put("bamount", amounts);
		jsonMaps.put("money",moneys);
		JSONArray array=new JSONArray();
		JSONObject object=new JSONObject();
		object.putAll(jsonMaps);
		array.add(object);
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("footer", array);
		maps.put("total", total);
		maps.put("rows", bills);
		System.out.println(JSON.toJSONString(maps));
		return JSON.toJSONString(maps);
	}
	
	@RequestMapping("getBillDetailList.json")
	@ResponseBody
	public Object getBillDetailList(String billCode){
		List<InstroageBillDetail> billDetails=detailService.finDetailsByBillCode(billCode);
		Map<String, Object> jsonMaps=new HashMap<String, Object>();
		int amounts=0;//数量总和
		double moneys=0;//总价总和
		for (InstroageBillDetail detail : billDetails) {
			amounts+=detail.getAmount();
		}
		for (InstroageBillDetail detail : billDetails) {
			moneys=moneys+(detail.getPrice()*detail.getAmount());
		}
		jsonMaps.put("isFooter", true);
		jsonMaps.put("partName", "合计");
		jsonMaps.put("amount", amounts);
		jsonMaps.put("money", moneys);
		JSONArray array=new JSONArray();
		JSONObject object=new JSONObject();
		object.putAll(jsonMaps);
		array.add(object);
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("footer", array);
		maps.put("rows", billDetails);
		maps.put("total", billDetails.size());
		return JSON.toJSONString(maps);
	}
	
	@RequestMapping("createInstroageBillCode")
	@ResponseBody
	public Object createCode(String firstCode){
		return JSON.toJSONString(makeNewCode.getRandomCodeByPrefix(firstCode));
	}
	
	@RequestMapping("getCompanyList.json")
	@ResponseBody
	public Object getCompanyList(@RequestParam(value="page",required=false)Integer page,
            @RequestParam(value="rows",required=false)Integer size,
            @RequestParam(value="code",required=false)String code,
            @RequestParam(value="name",required=false)String name,
            @RequestParam(value="type",required=false)Integer type
            ){
		Map<String, Object>maps=new HashMap<String, Object>();
		List<Integer> types=new ArrayList<Integer>();
		if(type==null){
			types.add(2);
		}else{
			types.add(type);
		}
		maps.put("total", companyService.getCompanyCount(types, name, code));
		maps.put("rows", companyService.getCompanys(types, name, code, page, size));
		return JSON.toJSONString(maps);
	}
	
	@RequestMapping("getInstroageType")
	@ResponseBody
	public Object getInstroageType(String type){
		return JSON.toJSONString(dictService.getDictListByType(type));
	}
	
	@RequestMapping("getSupplierOrderList.json")
	@ResponseBody
	public Object getSupplierOrderList(@RequestParam(value="page",required=false)Integer page,
            @RequestParam(value="rows",required=false)Integer size,
            @RequestParam(value="code",required=false)String code,
            @RequestParam(value="customName",required=false)String companyName,
            @RequestParam(value="fromDate",required=false)Date fromDate,
            @RequestParam(value="endDate",required=false)Date endDate){
		System.out.println(companyName);
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("total", pOrderBillService.getPurchaseOrderBillByCompanyNameCount(companyName, fromDate, endDate, code));
		maps.put("rows", pOrderBillService.getPurchaseOrderBillByCompanyName(companyName, page, size, fromDate, endDate, code));
		return JSON.toJSONString(maps);
	}
	@RequestMapping("getPartByCode.json")
	@ResponseBody
	public Object getPartByCode(@RequestParam(value="billCode[]",required=false) String[] billCode,
			                    @RequestParam(value="codes[]",required=false)String[] codes){
		Map<String, Object> jsonMaps=new HashMap<String, Object>();
		int amounts=0;//数量总和
		double moneys=0;//总价总和
		if(billCode==null&&codes==null){
			//String nullDate="{\"rows\":[],\"total\":0;\"footer\":[]}";
			return null;
		}else{
			List<Map<String, Object>> partList=null;
			if(billCode!=null&&codes!=null&&codes.length!=0){
				partList=pDetailService.getPurchaseOrderBillDetailListByBillCode(billCode);
				List<Map<String, Object>> partList2=partService.getPartListByCodes(codes);
				partList.addAll(partList2);
			}else if(billCode!=null&&codes==null){
				partList=pDetailService.getPurchaseOrderBillDetailListByBillCode(billCode);
			}else if(billCode==null&&codes!=null&&codes.length!=0){
				partList=partService.getPartListByCodes(codes);
			}
			for (Map<String, Object> part : partList) {
				amounts=((Integer) (part.get("amount")==null?1:part.get("amount")))+amounts;
			}
			Double price1=0.00;
			
			for (Map<String, Object> part : partList) {
				if(part.get("price")!=null){
					double price2=new Double(part.get("price").toString());
					price1=(double) price2;
				}
				moneys=moneys+(((Integer) (part.get("amount")==null?1:part.get("amount")))*price1);
			}
			jsonMaps.put("isFooter", true);
			jsonMaps.put("partBrand", "合计");
			jsonMaps.put("amount", amounts);
			jsonMaps.put("money", moneys);
			JSONArray array=new JSONArray();
			JSONObject object=new JSONObject();
			object.putAll(jsonMaps);
			array.add(object);
			Map<String, Object> maps=new HashMap<String, Object>();
			maps.put("footer", array);
			maps.put("rows", partList);
			maps.put("total", partList.size());
			return JSON.toJSONString(maps);
		}
	}
	@RequestMapping("getPartList.json")
	@ResponseBody
	public Object getPartList(@RequestParam(value="customName")String customName,
			@RequestParam(value="page")Integer page,
			@RequestParam(value="rows")Integer rows,
			@RequestParam(value="size",required=false)String size,
			@RequestParam(value="partNo",required=false)String partNo,
			@RequestParam(value="name",required=false)String name,
			@RequestParam(value="type",required=false)Integer type){
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("total", partService.getPartListCount(size, partNo, name, type));
		maps.put("rows", partService.getPartListAndCompanyName(customName, page, rows, size, partNo, name, type));
		return JSON.toJSONString(maps);
	}
	@RequestMapping("getPartTypeList.json")
	@ResponseBody
	public Object getPartTypeList(){
		PartType partType=new PartType();
		partType.setId(0);
		partType.setTypeName("--请选择--");
		List<PartType> lists=partTypeService.getPartTypeList();
		lists.add(0, partType);
		return lists;
	}
	
	@RequestMapping("saveInstroageBill.json")
	@ResponseBody
	public Object saveInstroageBill(@RequestParam(value="total")Double total,
			                        @RequestParam(value="codes")String codes,
			                        @RequestParam(value="inBill",required=false)String inBill){
		Map<String, Object>maps=new HashMap<String, Object>();
		if(instroageBillService.addInstroageBill(inBill, codes,total)){
			maps.put("result", "success");	
		}else{
			maps.put("result", "error");	
		}
		return JSON.toJSONString(maps);
	}
	
	@RequestMapping("modifyInstroageBill.html")
	public String modifyObjectPage(String code,HttpServletRequest request){
		InstroageBill inBill=instroageBillService.getInstroageBillByCode(code);
		request.setAttribute("inBill", inBill);
		return "web/goods/modifyInstroageBill";
	}
	@RequestMapping("getPartByInstroageCode.json")
	@ResponseBody
	public Object getPartByInstroageCode(@RequestParam(value="billCode[]",required=false) String[] billCode,
			@RequestParam(value="codes[]",required=false)String[] codes){
		Map<String, Object> jsonMaps=new HashMap<String, Object>();
		int amounts=0;//数量总和
		double moneys=0;//总价总和
		if(billCode==null&&codes==null){
			//String nullDate="{\"rows\":[],\"total\":0;\"footer\":[]}";
			return null;
		}else{
			List<Map<String, Object>> partList=null;
			List<Map<String, Object>> partList2=null;
			if(billCode!=null&&codes!=null&&codes.length!=0){
				if(billCode[0].substring(0, 2).equalsIgnoreCase("RK")){
					partList=detailService.findDetailByCode(billCode[0]);
					partList2=partService.getPartListByCodes(codes);
				}else{
					System.out.println("=================================================");
					partList=pDetailService.getPurchaseOrderBillDetailListByBillCode(billCode);
					System.out.println("partList==============="+JSON.toJSONString(partList));
					partList2=partService.getPartListByCodes(codes);
					System.out.println("partList2==============="+JSON.toJSONString(partList2));
				}
				partList.addAll(partList2);
			}else if(billCode!=null&&codes==null){
				if(billCode[0].substring(0, 2).equalsIgnoreCase("RK")){
					partList=detailService.findDetailByCode(billCode[0]);
				}else{
					partList=pDetailService.getPurchaseOrderBillDetailListByBillCode(billCode);
				}
			}else if(billCode==null&&codes!=null&&codes.length!=0){
				partList=partService.getPartListByCodes(codes);
			}
			for (Map<String, Object> part : partList) {
				amounts=((Integer) (part.get("amount")==null?1:part.get("amount")))+amounts;
			}
			Double price1=0.00;
			
			for (Map<String, Object> part : partList) {
				if(part.get("price")!=null){
					double price2=new Double(part.get("price").toString());
					price1=(double) price2;
				}
				moneys=moneys+(((Integer) (part.get("amount")==null?1:part.get("amount")))*price1);
			}
			jsonMaps.put("isFooter", true);
			jsonMaps.put("partBrand", "合计");
			jsonMaps.put("amount", amounts);
			jsonMaps.put("money", moneys);
			JSONArray array=new JSONArray();
			JSONObject object=new JSONObject();
			object.putAll(jsonMaps);
			array.add(object);
			Map<String, Object> maps=new HashMap<String, Object>();
			maps.put("footer", array);
			maps.put("rows", partList);
			maps.put("total", partList.size());
			System.out.println(JSON.toJSONString(maps));
			return JSON.toJSONString(maps);
		}
	}
	@RequestMapping("updateInstroageBill.json")
	@ResponseBody
	public Object updateInstroageBill(@RequestParam(value="total")Double total,
            @RequestParam(value="codes")String codes,
            @RequestParam(value="inBill",required=false)String inBill){
		Map<String, Object>maps=new HashMap<String, Object>();
		if(instroageBillService.modifyInstroageBill(inBill, codes, total)){
			maps.put("result", "success");	
		}else{
			maps.put("result", "error");	
		}
		return JSON.toJSONString(maps);
	}
	@RequestMapping("delrow.json")
	@ResponseBody
	public Object delRow(String code){
		Map<String, Object> maps=new HashMap<String, Object>();
		if(instroageBillService.delInstroageBillCode(code)){
			maps.put("result", "success");
		}else{
			maps.put("result", "error");
		}
		return JSON.toJSONString(maps);
	}
	@RequestMapping("delrows.json")
	@ResponseBody
	public Object delRows(@RequestParam("codes[]")String[] codes){
		Map<String, Object> maps=new HashMap<String, Object>();
		if(instroageBillService.delInstroageBillByArray(codes)){
			maps.put("result", "success");
		}else{
			maps.put("result", "error");
		}
		return JSON.toJSONString(maps);
	}
	@RequestMapping("checkStatusInstroageBill.json")
	@ResponseBody
	public Object checkStatusInstroageBill(String billCode){
		Map<String, Object> maps=new HashMap<String, Object>();
		if(instroageBillService.modifyInstroageBillCheckStatus(billCode)){
			maps.put("result", "success");
		}else{
			maps.put("result", "error");
		}
		return JSON.toJSONString(maps); 
	}
	@RequestMapping("cancelCheckStatusInstroageBill.json")
	@ResponseBody
	public Object cancelCheckStatusInstroageBill(String billCode){
		Map<String, Object> maps=new HashMap<String, Object>();
		if(instroageBillService.modifyCancelInstroageBillCheckStatus(billCode)){
			maps.put("result", "success");
		}else{
			maps.put("result", "error");
		}
		return JSON.toJSONString(maps);
	}
	@RequestMapping("getExcel.json")
	public void getExcel(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="page",required=false)Integer page,
            @RequestParam(value="rows",required=false)Integer size,
            @RequestParam(value="findcode",required=false)String findcode,
            @RequestParam(value="findstartDate",required=false)Date findstartDate,
            @RequestParam(value="findendDate",required=false)Date findendDate,
            @RequestParam(value="findsupplierName",required=false)String findsupplierName){
		//获取数据
				List<InstroageBill> list=instroageBillService.getInstroageBillList(page, size, findcode, findstartDate, findendDate, findsupplierName);
				/*List<PayBill> list=new ArrayList<PayBill>();
				for(int i=0;i<2;i++) {
					PayBill p=new PayBill();
					p.setCode(String.valueOf(i));
					p.setCustomName("qwe");
					p.setMemo("123");
					p.setPayDate(new Date());
					p.setPayStatus(1);
					p.setPayTotalMoney(2);
					p.setPayType(2);
					list.add(p);
				}*/
				System.out.println(list);

				//excel标题
				String[] title= {"入库单号","入库日期","供应商名称","数量","总货值","退货情况"
						,"付款情况","售票情况","审核情况","操作员"};
				System.out.println(title);

				//excel文件名
				String fileName="入库单管理"+new SimpleDateFormat("yyyy/MM/dd").format(new Date())+".xls";
				System.out.println(fileName);

				//sheet名
				String sheetName="入库单管理";
				System.out.println(sheetName);

				//装载数据
				String[][] content=new String[list.size()][title.length];
				for(int i=0;i<list.size();i++) {
					InstroageBill p=list.get(i);
					content[i][0]=p.getCode();
					content[i][1]=new SimpleDateFormat("yyyy/MM/dd").format((p.getInstroageDate()));
					content[i][2]=p.getCustomName();
					Integer amounts=0;
					Double moneys=(double) 0;
					for (InstroageBill instroageBill : list) {
						amounts+=instroageBill.getBamount();
					}
					for (InstroageBill instroageBill : list) {
						moneys+=instroageBill.getMoney();
					}
					content[i][3]=amounts.toString();
				    content[i][4]=String.valueOf(list.get(i).getMoney());
				    content[i][5]="0.00";
				    content[i][6]="0.00";
				    content[i][7]="0.00";
					if(p.getPayStatus()==1) {
						content[i][8]="未审核";
					}else if(p.getPayStatus()==2){
						content[i][8]="已审核";
					}
					content[i][9]="jr_democ";
				}
				System.out.println(content.toString());

				//创建HSSF
				HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
				System.out.println(wb+">>>>>>>>");

				//响应到客户端
				try {
					this.setResponseHeader(response, fileName);
					OutputStream os=response.getOutputStream();
					wb.write(os);
					os.flush();
					os.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}

			/** 
			 * @Title: setResponseHeader 
			 * @Description: 发送响应流方法
			 * @param response
			 * @param fileName  参数说明 
			 * @return void    返回类型 
			 * @throws 
			 */
			public void setResponseHeader(HttpServletResponse response, String fileName) {
				try {
					try {
						fileName = new String(fileName.getBytes(),"ISO8859-1");
					}catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					response.setContentType("application/octet-stream;charset=ISO8859-1");
					response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
					response.addHeader("Pargam", "no-cache");
					response.addHeader("Cache-Control", "no-cache");
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			}
			/** 
			 * @Title: getWord 
			 * @Description: TODO(这里用一句话描述这个方法的作用) 
			 * @param code
			 * @param request
			 * @param response  参数说明 
			 * @return void    返回类型 
			 * @throws 
			 */
			@RequestMapping("getWord.json")
			public void getWord(@RequestParam("code") String code,HttpServletRequest request,HttpServletResponse response) {
				System.out.println(code);

				// 获取应用的根路径
				String servletContextRealPath = request.getServletContext().getRealPath("");
				// 获取模板文件
				File templateFile = new File(servletContextRealPath + "/wordModel/instroageBillWordModel.docx");
				FileInputStream in=null;
				try {
					in = new FileInputStream(templateFile);
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				//生成word文件名
				String fileName="烟台凯旋科技有限公司入库单"+new SimpleDateFormat("yyyy/MM/dd").format(new Date())+".docx";

				//$替换对象
				InstroageBill p=instroageBillService.getInstroageBillByCode(code);
				Map<String,String> testMap=new HashMap<String, String>();
				testMap.put("code", p.getCode());
				testMap.put("name", p.getCustomName());
				testMap.put("linkman", p.getLinkman());
				testMap.put("date", new SimpleDateFormat("yyyy/MM/dd").format(p.getInstroageDate()));
				testMap.put("phone", p.getPhone());
				testMap.put("type", p.getInstroageType()==1?"采购入库":"其它入库");
				testMap.put("memo", p.getMemo());

				//需插入表格替换对象
				List<String[]> testList = new ArrayList<String[]>();
				//List<PayBillDetail> payBillDetailList= payBillDetailService.findPayBillDetail(code);
				List<InstroageBillDetail> list=detailService.finDetailsByBillCode(code);
				Integer amounts=0;
				for(int i=0;i<list.size();i++) {
					InstroageBillDetail ins=list.get(i);
					amounts+=ins.getAmount();
					testList.add(new String[]{ins.getBillCode(),ins.getPart().getPartNo(),ins.getPart().getPartName(),
							ins.getPart().getPartBrand(),ins.getPart().getPartTypeName(),String.valueOf(ins.getAmount()),
							String.valueOf(ins.getPrice()),String.valueOf(ins.getAmount()*ins.getPrice()),ins.getMemo()});
				}
				//写入合计金额
				testMap.put("amounts",String.valueOf(amounts));
				testMap.put("moneys",String.valueOf(p.getMoney()));
				WorderToNewWordUtils util=new WorderToNewWordUtils();
				XWPFDocument doc= util.changWord(in, testMap, testList, 8);
				//响应到客户端
				try {
					this.setResponseHeader(response, fileName);
					OutputStream os=response.getOutputStream();
					doc.write(os);
					os.flush();
					os.close();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			@RequestMapping("getPartPriceFive.json")
			@ResponseBody
			public Object getPartPriceFive(String partCode){
				return JSON.toJSONString(detailService.getInstroageBillDetailLimitFiveByPartCode(partCode));
			}
}
